import jwt
from jwt import exceptions
from rest_framework.response import Response
from datetime import datetime,timedelta
from django.conf import settings


from learning_platform.settings import SECRET_KEY
import jwt
from datetime import datetime, timedelta
import json

key = SECRET_KEY
# print('生成token的key是=>', key)


# 生成token
def generate_token(payload, expiry):
    # if 'expiry' not in payload:
    payload['expiry'] = expiry

    # 生成token
    try:
        print('获取到的json数据是', payload)
        token = jwt.encode(payload, key, algorithm='HS256')
    except Exception as e:
        print('生成token的报错信息是==>', e)
        return None
    return token


# 验证token
def check_token(token):
    # print('============', token)
    payload = jwt.decode(token, key, algorithms='HS256')
    return payload


# 生成两个token
def _generate_token(payload, refresh=True):
    try:
        expiry = datetime.now() + timedelta(hours=2)
        print('==========================expiry', expiry)
        token = generate_token(payload, str(expiry))  # 两小时的token
        print('生成的两小时token', token)
    except Exception as e:
        print('生成两小时的token报错信息=>', e)
        return None
    if refresh:
        try:
            expiry1 = datetime.now() + timedelta(days=15)
            print('==========================expiry1', expiry1)
            refresh_token = generate_token(payload, str(expiry1))  # 生成15天的token
            print('生成的15天token', refresh_token)
        except Exception as e:
            print('生成15天token的报错信息是=>', e)
            return None
        return token, refresh_token
    return token




